﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsFormsApplication1.Common;
using FanjiaHotelPlatform.utils.Kits;
using FanJiaCommon.Kits;
using JobBatDeal.SqlDbHelper;
using log4net;
using MySql.Data.MySqlClient;
using Quartz;
using Z.BulkOperations;
using JobBatDeal.DbHelper;
using MySqlX.XDevAPI.Relational;
using JobBatDeal.Common;
using DbHelperMySQL = JobBatDeal.DbHelper.DbHelperMySQL;
using ConvertKit = JobBatDeal.Common.ConvertKit;

namespace JobBatDeal.Jobs
{
    public class MeituanHotelUptJob : IJob
    {
        private readonly ILog _logger = LogManager.GetLogger(typeof(MeituanHotelUptJob));
        private static string SupplierId = "B8E0D4A6-AB99-444C-B1CB-75D1EA062EFC";

        public void Execute(IJobExecutionContext context)
        {
            _logger.InfoFormat("===***********MeituanHotelUptJob 执行开始*********===");



            _logger.InfoFormat("===***********MeituanHotelUptJob 执行完成*********===");
        }

        public void UptMeituanInfoByCity()
        {
            var dtProv = DbHelperSQL.Query("SELECT Id,Name FROM Provinces").Tables[0];

            if (dtProv != null && dtProv.Rows.Count > 0)
            {
                foreach (DataRow drProv in dtProv.Rows)
                {
                    _logger.InfoFormat($">>>>开始处理省份：{drProv["Name"].ToString()}");

                    var dtCity = DbHelperSQL.Query($"SELECT Id,Name FROM Cities WHERE Isdeleted =0 AND ProvinceId='{drProv["Id"].ToString()}'").Tables[0];

                    if (dtCity != null && dtCity.Rows.Count > 0)
                    {
                        foreach (DataRow drCity in dtCity.Rows)
                        {
                            _logger.InfoFormat($"---->>开始处理城市：{drCity["Name"].ToString()}");

                            var cityId = Guid.Parse(drCity["Id"].ToString());
                            //ToMeituanInfoByCity(cityId);

                            _logger.InfoFormat($"---->>城市处理完成：{drCity["Name"].ToString()}");
                        }
                    }

                    _logger.InfoFormat($">>>>省份：{drProv["Name"].ToString()} 结束>>>>");
                }
            }
        }

        public void ComHotelInfoByCity(Guid cityId)
        {
            //查询该城市下所有美团新更新的酒店
            var dtMeituanHotel = DbHelperMySQL
                    .Query($@"SELECT HotelId,HotelName,HotelDescript,AmapLatitude,AmapLongitude,Address,BusinessDistrict,AvgScore,FloorNum,Telephone,FrontImage,OpenYear,RenovationYear,RoomQuantity,StarRating,CheckInFrom,CheckOutTo,FanjiaFacilities,FanjiaKeywords,LocationId
                        FROM meituanhotelinfo WHERE FanjiaCityId='{cityId}'", "MysqlConn", "meituanhoteldata").Tables[0];

            //查询泛嘉酒店库中，该城市所有关联美团的酒店
            var strSql = $@"SELECT b.[Id], m.SupplierHotelId
                      ,[Name]
                      ,[Address]
                      ,[Phone]
                      ,[Longitude]
                      ,[Latitude]
                  FROM [HotelBasicInfoes] b,[HotelMappings] m 
                  where b.CityId='{cityId}' and m.hotelid=b.id and b.IsDeleted=0 and m.supplierid='{SupplierId}' and m.isdeleted=0";
            var dtFjHotel = DbHelperSQL.Query(strSql).Tables[0];

            //对比同一美团ID的酒店信息（酒店名词、电话、经纬度）
            if (dtMeituanHotel != null && dtMeituanHotel.Rows.Count > 0)
            {
                if (dtFjHotel.Rows.Count > 0)
                {
                    var dtHotelNew = DbHelperSQL.Query("SELECT * FROM HotelBicInfo_Meituan WHERE 1=0").Tables[0];

                    var dicHotelId = new Dictionary<Guid, int>();

                    foreach (DataRow dr in dtMeituanHotel.Rows)
                    {
                        var mtHotelId = dr["HotelId"].ToString();
                        var fjHotelRow = dtFjHotel.Select($"SupplierHotelId='{mtHotelId}'");

                        if (fjHotelRow != null && fjHotelRow.Length > 0)
                        {
                            foreach (DataRow drFj in fjHotelRow)
                            {
                                JudgeInfo(dr, drFj, dtHotelNew, cityId);
                            }                            
                        }
                    }


                    if (dtHotelNew.Rows.Count > 0)
                    {
                        //SaveDataTableSqlServer(dtHotelNew, "HotelBicInfo_Meituan");
                    }
                }
            }

            _logger.Info("OK!");
        }

        private static void JudgeInfo(DataRow drMt, DataRow dr, DataTable dtHotelNew, Guid cityId)
        {
            var fjName = dr["Name"].ToString();
            var fjPhone = dr["Phone"].ToString();
            var fjLat = ConvertKit.ToDecimal(dr["Latitude"]);
            var fjLngr = ConvertKit.ToDecimal(dr["Longitude"]);

            var mtName = drMt["HotelName"].ToString();
            var mtPhone = drMt["Telephone"].ToString();
            var mtLat = ConvertKit.ToDecimal(drMt["AmapLatitude"]);
            var mtLngr = ConvertKit.ToDecimal(drMt["AmapLongitude"]);

            var hotelNameSimilarity =
                Common.SimilarityGenerator.GetNameSimilarity(fjName, mtName);
            var hotelPhoneSimilarity =
                Common.SimilarityGenerator.GetPhoneSimilarity(fjPhone, mtPhone);

            var hotelCoordinateSimilarity = 0D;
            if (fjLat > 0 && fjLngr > 0 && mtLat > 0 && mtLngr > 0)
            {
                hotelCoordinateSimilarity =
                    Common.SimilarityGenerator.GetCoordinateSimilarity(fjLat, fjLngr, mtLat, mtLngr);
            }

            var isSame = false;
            //同一供应商名称一致，则通过
            if (fjName == mtName)
            {
                isSame = true;
            }
            //同一供应商名称不一致（名称相似度在90%以上）、电话一致、经纬度在200米范围内，则通过
            else if ((hotelNameSimilarity > 0.9D && hotelPhoneSimilarity == 1) ||
                     (hotelNameSimilarity >= 0.8D && hotelCoordinateSimilarity == 1) ||
                     (hotelNameSimilarity > 0.82D && hotelPhoneSimilarity == 1 &&
                      hotelCoordinateSimilarity >= 0.9D))
            {
                isSame = true;
            }

            if (isSame)
            {
                var drNew = dtHotelNew.NewRow();

                //drNew["Id"] = dr["Id"];
                //drNew["Name"] = row[0]["HotelName"];
                //drNew["StarRating"] = ConvertKit.ToInt32(row[0]["StarRating"], 1);
                //drNew["Address"] = row[0]["Address"];
                //drNew["EstablishmentDate"] = row[0]["OpenYear"];
                //drNew["RenovationDate"] = row[0]["RenovationYear"];
                //drNew["NumberOfRooms"] = row[0]["RoomQuantity"];
                //drNew["FloorHeight"] = row[0]["FloorNum"];
                //drNew["Phone"] = row[0]["Telephone"];
                //drNew["Introduction"] = row[0]["HotelDescript"];
                //drNew["Longitude"] = row[0]["AmapLongitude"];
                //drNew["Latitude"] = row[0]["AmapLatitude"];
                //drNew["CheckInTime"] = row[0]["CheckInFrom"];
                //drNew["CheckOutTime"] = row[0]["CheckOutTo"];

                //drNew["CityId"] = cityId;
                //drNew["Keywords"] = row[0]["FanjiaKeywords"];
                //drNew["ThumbImageUrl"] = row[0]["FrontImage"];
                //drNew["StarCategory"] = 2;
                //drNew["SupplierId"] = SupplierId;

                //drNew["TotalScore"] = ConvertKit.ToDecimal(row[0]["AvgScore"], 0);

                //var districtCode = row[0]["LocationId"].ToString();
                //if (!string.IsNullOrEmpty(districtCode) && districtCode.Length == 6)
                //{
                //    drNew["DistrictCode"] = districtCode;
                //}

                //var businessDistrictS = Convert.ToString(row[0]["BusinessDistrict"]);
                //if (!string.IsNullOrEmpty(businessDistrictS) && "无合适商圈" != businessDistrictS)
                //{
                //    drNew["BusinessDistrict"] = businessDistrictS.Replace('/', ',');
                //}

                //var fanjiaFacilities = row[0]["FanjiaFacilities"].ToString();
                //if (!string.IsNullOrEmpty(fanjiaFacilities))
                //{
                //    drNew["HotelFacilities"] = fanjiaFacilities;

                //    var facList = JsonKit.DeserializeJsonToList<HotelFacilityCategoryKit>(fanjiaFacilities);

                //    if (facList?.Count > 0)
                //    {
                //        var strFac = "";

                //        facList.ForEach(c =>
                //        {
                //            if (c.Items?.Count > 0)
                //            {
                //                c.Items.ForEach(i =>
                //                {
                //                    strFac = $"{strFac},{i.Title}";
                //                });
                //            }
                //        });

                //        drNew["Facilities"] = strFac.Trim(',');
                //    }
                //}

                dtHotelNew.Rows.Add(drNew);
            }
        }
    }
}
